import React, { useState } from "react";
import cs from "classnames";
import "./index.scss";
import CompactContext, { CompactContextProps } from "./CompactContext";

function Compact(props: { children: React.ReactElement[] }) {
  const [providers, setProviders] = useState<CompactContextProps>({});

  return (
    <CompactContext.Provider value={providers}>
      <div className="compact">
        {props.children.map((child, index) => {
          const { classNames = [], onFocus, onBlur } = child.props;

          function handleFocus<T>(...args: T[]) {
            setProviders({ ...providers, focus: true });
            onFocus?.(...args);
          }

          function handleBlur<T>(...args: T[]) {
            setProviders({ ...providers, focus: false });
            onBlur?.(...args);
          }
          // 通过 cloneElement 注入额外属性
          const enhancedChild = React.cloneElement(child, {
            // 添加自定义属性（示例）
            // 保留原有 props（自动合并）
            ...child.props,
            classNames: cs([
              ...classNames,
              "compact-space-item",
              index === 0 && "compact-first-item",
              index === React.Children.count(props.children) - 1 &&
                "compact-last-item",
            ]),
            onFocus: handleFocus,
            onBlur: handleBlur,
            key: index,
          });
          return enhancedChild;
        })}
      </div>
    </CompactContext.Provider>
  );
}

export default Compact;
